import { Form, Table } from 'antd';
import React, { useEffect, useImperativeHandle, useMemo, useState } from 'react';
import '../common/style.less';
import { getKeyRouter, getLoadMapList, getTenantID } from '@/utils';
import { ILoadMapTypeAll } from '@/common';
import { SourceUpdateAPI } from '../common/type';
import { getExtractTableConfig } from '../mconfig';

export const ExtractListFirstStep = React.forwardRef<SourceUpdateAPI.IExtractListFormRef, SourceUpdateAPI.IFirstStep>(({ current }, ref) => {
  /**extract表单的ref*/
  const [extractForm] = Form.useForm();

  useImperativeHandle(
    ref,
    () =>
      ({
        firstStepForm: extractForm,
      } as any),
  );

  const loadMdicIds: string[] = [`${getTenantID()}${ILoadMapTypeAll.EXPERTS_TYPE}`];
  const { loadMapInfo, mapLoading } = getLoadMapList(loadMdicIds);

  // const setTableRowClassName = (_: Record<string, any>, index: number) => {
  //   return index % 2 == 0 ? 'double-row' : 'default-row';
  // };

  /** 表格分页方法改变事件 */
  // const handlePaginationChange = () => {};

  /** 保存供货数据 */
  const [materialDataSource, setMaterialDataSource] = useState<Record<string, any>[]>(extractForm?.getFieldValue('extractTable'));

  useEffect(() => {
    extractForm?.setFieldsValue({
      extractTable: materialDataSource?.length > 0 ? materialDataSource : [],
    });
  }, [materialDataSource?.length]);

  /** 添加供货 */
  const addMaterialCallback = () => {
    const addItemObj: Record<string, any> = {
      key: `extractTable-${getKeyRouter()}`,
      modifyFlag: 0,
    };
    let changeList: Record<string, any>[] = [];
    changeList?.push(addItemObj);
    setMaterialDataSource((_prevState: Record<string, any>[]) => {
      const materFormValue: Record<string, any>[] = extractForm?.getFieldValue('extractTable');
      let newMaterial: Record<string, any>[] = [...materFormValue];
      newMaterial?.push(addItemObj);
      return newMaterial;
    });
  };

  /** 删除附件 */
  const delMaterialCallback = (resObj: Record<string, any>) => {
    let newChangeList: Record<string, any>[] = extractForm?.getFieldValue('extractTable')?.length > 0 ? extractForm?.getFieldValue('extractTable') : [];
    if (resObj && resObj?.id) {
      const delObj: Record<string, any> = {
        ...resObj,
      };
      newChangeList = newChangeList.filter((item: any) => item?.id != delObj?.id);
    }
    setMaterialDataSource(newChangeList);

    // const changeList: Record<string, any>[] =
    //   contarctJsonList?.['detailList']?.length > 0 ? contarctJsonList?.['detailList'] : [];
    // if (resObj && resObj?.id) {
    //   const delObj: Record<string, any> = {
    //     ...resObj,
    //     modifyFlag: '2',
    //   };
    //   newChangeList = changeList?.filter((item: any) => item?.id != delObj?.id);
    //   newChangeList?.push(delObj);
    // } else if (resObj && resObj?.key) {
    //   newChangeList = changeList?.filter((item: any) => item?.key != resObj?.key);
    // }
    // contractDispatch({
    //   type: IContractsActionEnum.CONTRACT_JSONLIST,
    //   payload: {
    //     ...contarctJsonList,
    //     detailList: newChangeList,
    //   },
    // });
    // setMaterialDataSource((_prevState: Record<string, any>[]) => {
    //   const newDetailList: Record<string, any>[] = contractForm?.getFieldValue('detailList');
    //   const newMaterial: Record<string, any>[] = newDetailList?.filter((item: any) => {
    //     if (item?.id) {
    //       return item?.id != resObj?.id;
    //     } else {
    //       return item?.key != resObj?.key;
    //     }
    //   });
    //   return newMaterial;
    // });
  };

  /** 表格行配置 */
  const columnsMemo = useMemo(() => {
    return getExtractTableConfig(addMaterialCallback, delMaterialCallback, extractForm, loadMapInfo, mapLoading);
  }, [materialDataSource, loadMapInfo, mapLoading]);

  return (
    <div className={`list-table ExtractModalTable`} style={{ display: current === 0 ? 'block' : 'none' }}>
      <Form form={extractForm}>
        <Form.Item name="extractTable" valuePropName="dataSource">
          <Table
            columns={columnsMemo}
            bordered
            size="small"
            dataSource={materialDataSource}
            rowKey={(res) => (res?.id ? res?.id : res?.key)}
            scroll={{ x: 1200, y: '' }}
            pagination={false}
          />
        </Form.Item>
        {/* <Form.Item name="extractTable" valuePropName="dataSource">
            <Table
              size="small"
              bordered
              scroll={{ x: 1000, y: 1000 }}
              style={{ margin: '0' }}
              rowClassName={setTableRowClassName}
              // loading={getProjectLoading}
              dataSource={[]}
              columns={getExtractTableConfig(extractForm)}
              rowKey={'id'}
              pagination={{
                showQuickJumper: true,
                showSizeChanger: true,
                pageSizeOptions: commonPageSizeOptions,
                showTotal: showTotalInfo,
                onChange: handlePaginationChange as any,
                pageSize: 10,
                current: 1,
                total: 1,
              }}
            />
          </Form.Item> */}
      </Form>
    </div>
  );
});
